package com.example.demo.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class JwtUtils {
    /**
     * 生成令牌
     */
    private static String secretString = "HANcHZRUWrcBdZs0k2fOLZRT6eZSPgsZyGjjcXc2ric=";
    private static Key key  = Keys.hmacShaKeyFor(Decoders.BASE64URL.decode(secretString));
    private static long expiration =30*60*1000 ; //30 分钟后过期


    public static String getJwt(Map<String,Object> claims){

        String compact = Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis()+expiration))
                .signWith(key)
                .compact();

        return compact;
    }



    /**
     * 校验令牌
     */


    public static Claims verify(String token){

        //只有token相同,令牌才能校验成功
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        try{
            claims = build.parseClaimsJws(token).getBody();//token可能不合法
        } catch (ExpiredJwtException e){
            log.error("token 过期,校验失败,token: "+token);

        }catch (Exception e){
            log.error("token 校验失败,token : "+ token);
        }
        return claims;


    }

    public static Integer getUserIdFromToken(String token){
        Claims claims = verify(token);
        Assert.notNull(claims,"token不合法");
        Integer userId = (Integer) claims.get("id");
        return userId;
    }
}
